package com.cdxy.model.dto.base.redis;

import com.cdxy.enums.redis.IRedisCacheGroup;
import com.cdxy.model.dto.base.redis.service.RedisService;
import com.cdxy.model.dto.base.redis.util.KeyGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * @Author: tangy
 * @Date: 2020/2/21 16:47
 */
@Service
@Slf4j
public class RedisLockManager {

    private RedisService redisService;

    private KeyGeneratorUtil keyGeneratorUtil;

    public RedisLockManager(RedisService redisService, KeyGeneratorUtil keyGeneratorUtil) {
        this.redisService = redisService;
        this.keyGeneratorUtil = keyGeneratorUtil;
    }


    public boolean lock(IRedisCacheGroup redisCacheGroup, String key, int lockSecond) {
        if (redisCacheGroup == null || StringUtils.isBlank(key)) {
            log.error("参数错误，加锁失败。group:{},key:{}", redisCacheGroup, key);
            return false;
        }
        String result = redisService.setNX(this.keyGeneratorUtil.generateCacheKey(redisCacheGroup, key), key, lockSecond);
        return "OK".equalsIgnoreCase(result);
    }

    public void unlock(IRedisCacheGroup redisCacheGroup, String key) {
        if (redisCacheGroup == null || StringUtils.isBlank(key)) {
            log.error("参数错误，解锁失败。group:{},key:{}", redisCacheGroup, key);
            return;
        }
        redisService.del(this.keyGeneratorUtil.generateCacheKey(redisCacheGroup, key));
    }

}
